﻿using ConfExpert.Forms;
using ConfExpert.Forms.Araclar;
using DevExpress.LookAndFeel;
using DevExpress.XtraEditors;
using DevExpress.XtraNavBar;
using eFatura.Properties;
using eFatura.Utility;
using eFatura.Utility.Ribbon;
using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;

namespace eFatura
{
    public partial class MainForm : XtraForm
    {
        public int WhoAmI = AppSession.UserInfo.UserId;

        Dictionary<string, XForm> forms = new Dictionary<string, XForm>();

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            switch (AppSession.SirketId)
            {
                case 1:
                    Fatura.Init("taylank", "123+Asd", 1123);
                    break;
                case 2:
                    Fatura.Init("karbeldis", "123+Sdf", 1122);
                    break;
                case 3:
                    Fatura.Init("ersur", "123+Sdf", 1121);
                    break;
                case 4:
                    Fatura.Init("aker", "123+Sdf", 1124);
                    break;
                case 5:
                    Fatura.Init("sibel", "123+Sdf", 1041);
                    break;
            }

            this.KeyDown += MainForm_KeyDown;
            this.MdiChildActivate += MainForm_MdiChildActivate;

            this.Text = "Karbel e-Fatura Adaptörü" + (AppSession.Version != null ? " - v" + AppSession.Version : "");

            bsiUser.Caption = eFatura.Utility.AppSession.UserInfo.UserName;
            UserLookAndFeel.Default.SetSkinStyle(Login.SkinName);
            this.WindowState = FormWindowState.Maximized;

            if (AppSession.SirketId == 6)
            {
                ShowMdiChildForm(typeof(EDefter));
                return;
            }

            //new RibbonManager(Ribbon);
            RepositoryManager.Init();
            InitDagilim();

            dockMenu.Text = AppSession.Sirket;

            if (!AppSession.UserInfo.Yonetici)
            {
                nbEntegrasyon.Visible = false;
                nbGiden.Visible = false;
                nbEDefter.Visible = false;
            }

            if (AppSession.UserInfo.UserId == 19) //ziynet bora
            {
                nbGiden.Visible = true;
            }

            DateTime sonEfaturaGuncelle = (DateTime)AppSession.DataManager.ExecuteScalar("GetAyar", "SonEfaturaMukellefGuncelleme", AppSession.SirketId);

            if (sonEfaturaGuncelle.ToShortDateString() != DateTime.Now.ToShortDateString())
            {
                XtraMessageBox.Show("e-Fatura mükelleflerinin güncellenmesi gerekiyor. Lütfen bu sırada programı kapatmadan bekleyin", "Uyarı", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Cursor = Cursors.WaitCursor;
                Fatura fatura = new Fatura();
                fatura.eFaturaMukellefGuncelle(true, AppSession.SirketId);
                this.Cursor = Cursors.Default;
                XtraMessageBox.Show("e-Fatura mükelleflerinin güncellenmesi tamamlandı. Çalışmanıza devam edebilirsiniz.", "Uyarı", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        public void InitDagilim()
        {
            DataSet ds = AppSession.DataManager.ExecuteDataSet(AppSession.Schema + "GetDagilim", AppSession.SirketId, WhoAmI);

            nbGiden.ItemLinks.Clear();
            DataTable dtGiden = ds.Tables[0];
            for (int i = 0; i < dtGiden.Rows.Count; i++)
            {
                DataRow dr = dtGiden.Rows[i];
                DevExpress.XtraNavBar.NavBarItemLink li = nbGiden.AddItem();
                li.Item.Caption = dr["FaturaDurum"] + " (" + dr["Adet"] + ")";
                li.Item.Tag = dr["FaturaDurum"];
                li.Item.LinkPressed += ItemGiden_LinkPressed;

                switch (dr["FaturaDurum"].ToString())
                {
                    case "Gönderilmemiş":
                        li.Item.SmallImage = Resources.mail_16x16;
                        break;
                    case "Hatalı":
                        li.Item.SmallImage = Resources.cancel_16x16;
                        break;
                    case "Başarılı":
                        li.Item.SmallImage = Resources.apply_16x16;
                        break;
                    case "Yanıt Bekleniyor":
                        li.Item.SmallImage = Resources.assignto_16x16;
                        break;
                    case "İşleniyor":
                        li.Item.SmallImage = Resources.properties_16x16;
                        break;
                }

                if (i == dtGiden.Rows.Count - 2 && dtGiden.Rows[i + 1]["FaturaDurum"].ToString() == "Tümü")
                {
                    nbGiden.ItemLinks.Add(new NavBarSeparatorItem());
                }
            }

            nbGiden.Expanded = true;


            nbGelen.ItemLinks.Clear();
            DataTable dtGelen = ds.Tables[1];
            for (int i = 0; i < dtGelen.Rows.Count; i++)
            {
                DataRow dr = dtGelen.Rows[i];
                DevExpress.XtraNavBar.NavBarItemLink li = nbGelen.AddItem();
                li.Item.Caption = dr["FaturaDurum"] + " (" + dr["Adet"] + ")";
                li.Item.Tag = dr["FaturaDurum"];
                li.Item.LinkPressed += ItemGelen_LinkPressed;

                switch (dr["FaturaDurum"].ToString())
                {
                    case "Yeni":
                        li.Item.SmallImage = Resources.newmail_16x16;
                        break;
                    case "Muhasebeye Aktarılan":
                        li.Item.SmallImage = Resources.apply_16x16;
                        break;
                }

                if (i == dtGelen.Rows.Count - 2 && dtGelen.Rows[i + 1]["FaturaDurum"].ToString() == "Tümü")
                {
                    nbGelen.ItemLinks.Add(new NavBarSeparatorItem());
                }
            }

            nbGelen.Expanded = true;
        }

        void ItemGiden_LinkPressed(object sender, NavBarLinkEventArgs e)
        {
            ShowMdiChildForm(typeof(GidenFatura), e.Link.Item.Tag.ToString());
        }

        void ItemGelen_LinkPressed(object sender, NavBarLinkEventArgs e)
        {
            ShowMdiChildForm(typeof(GelenFatura), e.Link.Item.Tag.ToString());
        }

        private void MainForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.F12)
            {
                MessageBox.Show(AppSession.DataManager.ConnectionString);
            }
            if (RibbonManager.isDeveloper)
            {
                if (e.Control && e.KeyCode == Keys.F2)
                {
                    ShowMdiChildForm(typeof(UserChanger));
                }
            }
        }

        private void MainForm_Shown(object sender, EventArgs e)
        {
            AppSession.MainForm.ShowInTaskbar = true;

            XmlParse x = new XmlParse();
            x.Pars();
        }

        private void MainForm_MdiChildActivate(object sender, EventArgs e)
        {
            XForm frm = (XForm)this.ActiveMdiChild;
            NotifySelectionInfo(frm);
        }

        public XForm GetActiveForm(Type type, params object[] prm)
        {
            XForm frm;
            string hash = GetHash(type, prm);

            forms.TryGetValue(hash, out frm);

            if (frm != null)
                if (!frm.IsDisposed)
                {
                    frm.Activate();
                    return frm;
                }
                else
                    forms.Remove(hash);

            return null;
        }

        private string GetHash(Type type, object[] prm)
        {
            string prmHash = "";
            foreach (object o in prm)
                prmHash += o.GetHashCode();

            return type.GetHashCode() + "." + prmHash;
        }

        public XForm ActiveXForm = null;

        public void SetActiveXFormFromMDIManager()
        {
            if (mdiManager.SelectedPage == null)
                ActiveXForm = null;
            else
            {
                XForm activeForm = mdiManager.SelectedPage.MdiChild as XForm;
                ActiveXForm = activeForm;
            }
        }

        private void mdiManager_SelectedPageChanged(object sender, EventArgs e)
        {
            SetActiveXFormFromMDIManager();
        }

        public XForm ShowMdiChildForm(Type type, params object[] prm)
        {
            XForm frm = GetActiveForm(type, prm);

            if (frm != null)
            {
                ActiveXForm = frm;
                return frm;
            }

            try
            {
                if (type.BaseType == typeof(XPopupForm))
                {
                    using (XPopupForm popup = (XPopupForm)Activator.CreateInstance(type, prm))
                    {
                        //AppSession.DataManager.ExecuteNonQuery("InsLogForm", WhoAmI, popup.GetType().ToString());
                        ActiveXForm = popup;
                        frm = popup;
                        popup.ShowDialog();
                    }
                }
                else
                {
                    frm = (XForm)Activator.CreateInstance(type, prm);
                    frm.MdiParent = this;
                    frm.WindowState = FormWindowState.Maximized;
                    string hash = GetHash(type, prm);
                    forms.Add(hash, frm);
                    //AppSession.DataManager.ExecuteNonQuery("InsLogForm", WhoAmI, frm.GetType().ToString());
                    ActiveXForm = frm;
                    frm.Show();
                }
            }
            catch (Exception Ex)
            {
                XtraMessageBox.Show(Ex.InnerException.ToString());
            }
            finally
            {

            }

            return frm;
        }

        public void NotifySelectionInfo(XForm frm)
        {
            if (frm != null && !frm.IsDisposed)
                bsiCustomSelectionInfo.Caption = frm.SelectionInfo;
        }

        public void NotifyMain(string message)
        {
            bsiInfo.Caption = DateTime.Now.ToLongTimeString() + " | " + message;
        }


        private void navBarItem1_LinkPressed_1(object sender, NavBarLinkEventArgs e)
        {
            ShowMdiChildForm(typeof(GelenFatura), "Tümü");
        }

        private void btnOnay_LinkPressed(object sender, NavBarLinkEventArgs e)
        {
            ShowMdiChildForm(typeof(Yetkilendirme));
        }

        private void btnEsleMal_LinkPressed(object sender, NavBarLinkEventArgs e)
        {
            ShowMdiChildForm(typeof(EslemeMalHizmet));
        }

        private void btnEsleFirma_LinkPressed(object sender, NavBarLinkEventArgs e)
        {
            ShowMdiChildForm(typeof(EslemeFirma));
            // new Fatura().eFaturaCariGuncelle();
        }

        private void btnFirmaSorgula_LinkPressed(object sender, NavBarLinkEventArgs e)
        {
            ShowMdiChildForm(typeof(FirmaSorgulama));
        }

        private void nbEDefter_LinkPressed(object sender, NavBarLinkEventArgs e)
        {
            ShowMdiChildForm(typeof(EDefter));
        }

        private void nbXMLInvoice_LinkPressed(object sender, NavBarLinkEventArgs e)
        {
            ShowMdiChildForm(typeof(XMLInvoice));
        }
    }
}